import pymongo
# 1.连接数据库服务器,获取客户端对象
mongo_client=pymongo.MongoClient('172.16.20.79',27017)


# 插入文档
def inser_news_range(items):
    db = mongo_client.local
    my_collection = db.baidu_hot
    my_collection.insert(items)

def fing_lastest_range(type=None):
    """
    返回最新搜索热词
    :param type: 可以按类型返回
    :return: 
    """
    db = mongo_client.local
    my_collection = db.baidu_hot


    last_time = get_last_time()

    if type:
        cursor = my_collection.find({'created': last_time, 'type':type},{'_id':0})
    else:
        cursor = my_collection.find({'created': last_time},{'_id':0})

    return list(cursor)


def get_last_time(db_name='baidu_hot', options=None):
    """
    找记录的最新更新时间
    :param db_name: 数据库名字
    :param options: 是否带参数搜索
    :return: 
    """
    db = mongo_client.local
    my_collection = db.baidu_hot

    if db_name== 'baidu_zone_hot':
        my_collection = db.baidu_zone_hot

    if options:
        cursor = my_collection.find(options).sort('created', pymongo.DESCENDING).limit(1)
    else:
        cursor = my_collection.find().sort('created', pymongo.DESCENDING).limit(1)

    return list(cursor)[0]['created']

# 插入主题地区搜索热词
def inser_zone_range(item):
    db = mongo_client.local
    my_collection = db.baidu_zone_hot
    my_collection.insert(item)

def find_lastest_zone_range(options):
    """
    :param zone: 地区码 
    :param name: 主题
    :return: 最新的热词
    """
    db = mongo_client.local
    my_collection = db.baidu_zone_hot
    last_time = get_last_time(db_name='baidu_zone_hot', options=options)

    options['created'] = last_time
    cursor = my_collection.find(options,{'_id':0}).sort('created', pymongo.DESCENDING).limit(1)

    return list(cursor)

if __name__ == '__main__':
    get_last_time()